#! /usr/bin/python
# -*- coding:utf-8 -*-

## ========================================================================
## Copyright (C) 2007-2013  Jean-Philippe GOLAY
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
## ========================================================================
 
import MySQLdb
import logging
from variable import *

class ManageDB:

  def __init__(self, dbName, user, passwd, host, port=3306):
    logging.basicConfig(filename=Glob.LOG_FILENAME,level=logging.DEBUG)
    try:
      self.con = MySQLdb.connect(db=dbName,user=user,passwd=passwd,host=host,port=port)
    except Exception, error:
      logging.debug(u'ManageDB __init__ Database error : %s' % error)
      self.failure=1
    else:
      self.con.set_character_set('utf8')     
      self.cursor=self.con.cursor()
      self.cursor.execute(u'SET NAMES utf8;')
      self.cursor.execute(u'SET CHARACTER SET utf8;')
      self.cursor.execute(u'SET character_set_connection=utf8;')       
      self.failure=0

  def createTables(self, dicTables):
    for tables in dicTables:        
      for table in dicTables[tables]:
        sql = "%s" % table
        self.executSQL(sql)

  def deleteTables(self, dicTables):
    for table in dicTables.key():
      sql = u"DROP TABLE %s" % table
      self.executSQL(sql) 
      self.commit()                 

  def executSQL(self, sql):
    try:
      self.cursor.execute(sql)
    except Exception, error:
      logging.debug(u'ManageDB executSQL Database error : %s' % error)
      return 0
    else:
      return 1

  def resultSQL(self):
    return self.cursor.fetchall()

  def commit(self):
    if self.con:
      self.con.commit()

  def close(self):
    if self.con:
      self.con.close()
